import AbsWindow from "../../framework/AbsWindow";
import { WindowName } from "../../framework/reflect/WindowName";
import Toast from "../popups/Toast";
import ShowWeaponInfoPopup from "../popups/ShowWeaponInfoPopup";
import { userInfoButton } from "../../framework/wx/UserInfoButtonHelper";
import { WxEvent } from "../../framework/wx/WxEvent";
import FightWindow from "./FightWindow";
import GameWindow from "./GameWindow";
import LocalStorage from "../../framework/utils/LocalStorage";
import CommonUtil from "../../framework/utils/CommonUtil";
import WeaponWindow from "./WeaponWindow";
import { shareUtil } from "../../framework/wx/ShareUtil";
import { userProfile } from "../entity/UserProfile";
import { wxApi } from "../api/WxApi";
import Context from "../../framework/Context";
import Handler from "../../framework/handler/Handler";
import ClickEventHandler from "../../framework/utils/events/ClickEventHandler";
import MessageDelegate from "../../framework/handler/MessageDelegate";
import LoadResData from "../../framework/LoadResData";
import TalentPopup from "../popups/TalentPopup";
import ForgeWindow from "./ForgeWindow";
import FBWindow from "./FBWindow";
import { SubContextView } from "../comp/SubContextView";
import SubWindow from "./SubWindow";
import MidasTouchWindow from "./MidasTouchWindow";

const { ccclass, property } = cc._decorator;

/**
 * 主窗口.
 */

@ccclass
@WindowName("MenuWindow")
export default class MenuWindow extends AbsWindow {

    @property(cc.Label)
    private goldLabel: cc.Label = null;
    @property(cc.Node)
    private weapon1: cc.Node = null;
    @property(cc.Node)
    private weapon2: cc.Node = null;
    @property(cc.Node)
    private weapon3: cc.Node = null;
    @property(cc.Node)
    private weapon4: cc.Node = null;
    @property(cc.Node)
    private talent1: cc.Node = null;
    @property(cc.Node)
    private talent2: cc.Node = null;
    @property(cc.Node)
    private talent3: cc.Node = null;
    @property(cc.Node)
    private talent4: cc.Node = null;
    @property(cc.Node)
    private talent5: cc.Node = null;
    @property(cc.Node)
    private mingrentang: cc.Node = null;
    @property(cc.Node)
    private mingrenzhanchang: cc.Node = null;
    @property(cc.Node)
    private dianshichengjin: cc.Node = null;
    @property(cc.Node)
    private duanzao: cc.Node = null;
    @property(cc.Node)
    private MidasTouch: cc.Node = null;
    private timer = null;

    public onStart() {
        //localStorage.clear();
        if (!LocalStorage.getObj("Player")) {
            var playerObj = {
                "gold": 100000,
                //自己的武器（等级，当前等级强化百分比状态，强化所需金币）
                oneselfWeapon: {
                    lv: 1,
                    curLvState: 0.6
                },
            }
            LocalStorage.setObj("Player", playerObj);
        }
        //已经拥有武器（武器ID，强化等级）
        if (!LocalStorage.getObj("weaponLv")) {
            var weaponLv = [
                { "id": 1, "lv": 1 },
                { "id": 2, "lv": 1 },
                { "id": 3, "lv": 1 },
                { "id": 4, "lv": 1 }
            ]
            LocalStorage.setObj("weaponLv", weaponLv);
        }
        //天赋（第一个ID，第二个激活状态；0未激活，1激活）
        if (!LocalStorage.getObj("talent")) {
            var talentList = [
                { "id": 1, "state": 0 },
                { "id": 2, "state": 0 },
                { "id": 3, "state": 0 },
                { "id": 4, "state": 0 },
                { "id": 5, "state": 0 },
            ]
            LocalStorage.setObj("talent", talentList);
        }
        //展示的武器 ID 0 未显示有倒计时 1显示 2未显示没倒计时
        if (!LocalStorage.getObj("showWeapon")) {
            var showWeaponList = [
                { "id": 1, "state": 1 },
                { "id": 2, "state": 1 },
                { "id": 3, "state": 1 },
                { "id": 4, "state": 0 }
            ]
            LocalStorage.setObj("showWeapon", showWeaponList);
        }
        //副本数据
        if (!LocalStorage.getObj("FBData")) {
            var data = [
                { "id": 0, "startTime": 0 },
                { "id": 0, "startTime": 0 },
                { "id": 0, "startTime": 0 },
                { "id": 0, "startTime": 0 },
                { "id": 0, "startTime": 0 },
                { "id": 0, "startTime": 0 },
                { "id": 0, "startTime": 0 },
                { "id": 0, "startTime": 0 },
            ]
            LocalStorage.setObj("FBData", data);
        }

        cc.log("playerObj", LocalStorage.getObj("Player"));
        cc.log("weaponLv", LocalStorage.getObj("weaponLv"));
        cc.log("talent", LocalStorage.getObj("talent"));
        cc.log("showWeapon", LocalStorage.getObj("showWeapon"));
        cc.log("FBData", LocalStorage.getObj("FBData"));

        for (let i = 0; i < 4; i++) {
            this.setClickListener(this["weapon" + (i + 1)], this.onClickWeapon);
        }
        for (let i = 0; i < 5; i++) {
            this.setClickListener(this["talent" + (i + 1)], this.onClickTalent);
        }
        this.setClickListener(this.mingrentang, this.onClickmingrentang);
        this.setClickListener(this.mingrenzhanchang, this.onRankList);
        this.setClickListener(this.dianshichengjin, this.onClickdianshichengjin);
        this.setClickListener(this.duanzao, this.onClickduanzao);
        this.setClickListener(this.MidasTouch,this.onMidasTouch);

        shareUtil.initShareMenu("ssss", "");
        userInfoButton.needShow().then((ret) => {
            if (ret) {
                return;
            }
            userInfoButton.show(userInfo => {
                if (userInfo) {
                    cc.log("获取到用户信息:", userInfo);
                    userProfile.name = userInfo.name;
                    userProfile.avatar = userInfo.avatarUrl;
                    userProfile.save();
                    wxApi.updateUserInfo(
                        userInfo.nickName, userInfo.avatarUrl, userInfo.gender,
                        userInfo.country, userInfo.province, userInfo.city);
                } else {
                    cc.log("玩家未授权");
                }
            });
        })
        this.onShowUI();
        this.showTalent();
    }

    public listen(): string[] {
        return [WxEvent.ON_HIDE, WxEvent.ON_SHOW, WxEvent.ON_CHANGETALENT, WxEvent.ON_CHANGEGOLD];
    }

    public handleMessage(msg: string, args: any[]): boolean {
        var self = this;
        switch (msg) {
            case WxEvent.ON_SHOW: {
                cc.log("WxEvent.ON_SHOW", args[0])
                break;
            }
            case WxEvent.ON_HIDE: {
                cc.log("WxEvent.ON_HIDE")
                break;
            }
            case WxEvent.ON_CHANGETALENT: {
                cc.log("WxEvent.ON_CHANGETALENT", args[0])
                MenuWindow.activateTalent(self, args[0])
                break;
            }
            case WxEvent.ON_CHANGEGOLD: {
                cc.log("WxEvent.ON_CHANGEGOLD", args[0])
                MenuWindow.upDataGold(self, args[0])
                break;
            }
        }
        return false;
    }

    private onStartGameClick() {

    }
    private onClickWeapon(e: cc.Event.EventTouch) {
        //StartPopup.showUI(e.currentTarget);
        //GameWindow.getData(e.currentTarget);
        var playerObj = LocalStorage.getObj("Player");
        cc.log(e.currentTarget)
        var str = e.currentTarget.name;
        var spstr = str.split("");
        var index = spstr[spstr.length - 1];
        var showWeapon: any = LocalStorage.getObj("showWeapon");
        var list = [];
        var weaponData = this.getWeaponData(index)
        var curWeaponLv = this.getWeaponLv(index)
        list.push(weaponData);
        list.push(curWeaponLv);
        for (let i = 0; i < showWeapon.length; i++) {
            if (index == showWeapon[i]["id"]) {
                if (showWeapon[i]["state"] == 1) {
                    ShowWeaponInfoPopup.showUI(list);
                }
                else if (showWeapon[i]["state"] == 0) {

                }
            }
        }

    }
    private onClickTalent(e: cc.Event.EventTouch) {
        var str = e.currentTarget.name;
        var spstr = str.split("");
        var index = spstr[spstr.length - 1];
        var data = LocalStorage.getObj("talent");
        var talentData = data[index - 1];
        TalentPopup.showTalent(talentData);
    }
    private onClickmingrentang() {
        this.context.startWindow(WeaponWindow);
    }
    private onRankList() {
        this.context.startWindow(SubWindow);
    }
    private onClickdianshichengjin() {
        this.context.startWindow(FBWindow);
    }
    private onClickduanzao() {
        this.context.startWindow(ForgeWindow);
    }
    private onMidasTouch(){
        this.context.startWindow(MidasTouchWindow);
    }
    //显示UI
    private onShowUI() {
        SubContextView.updateUserData("lv",{"level":1,"uuid":0,"timestamp":0,"wxgame":{}});
        var playerObj = LocalStorage.getObj("Player");
        var showWeapon: any = LocalStorage.getObj("showWeapon");
        this.goldLabel.string = playerObj["gold"];
        var sp, url, curPrefab;
        // 0 显示倒计时 ，1显示武器 
        var self = this
        for (var i = 0; i < showWeapon.length; i++) {
            if (showWeapon[i]["state"] == 0) {
                this.timer = setTimeout(self.showTime.bind(self), 1000, 300, i + 1);
                url = ''
            }
            else if (showWeapon[i]["state"] == 2) {
                url = ''
            }
            else {
                //显示对应武器
                this["weapon" + (i + 1)].activa = false;
                url = 'image/ren'
            }
            cc.log("weapon", this["weapon" + (i + 1)]);
            sp = this["weapon" + (i + 1)].getChildByName("image").getComponent(cc.Sprite);
            this.getSprite(url, sp);
        }
    }
    private showTalent() {
        var talentData: any = LocalStorage.getObj("talent");
        var sp, url;
        for (let index in talentData) {
            if (Number(index) > 4) { return };
            sp = this["talent" + (Number(index) + 1)].getComponent(cc.Sprite);
            talentData[index]['state'] == 0 ? url = "image/skill 2" : url = "image/skill";
            this.getSprite(url, sp);
        }
    }
    private showTime(num, index): any {
        var self = this;
        var h, s;
        h = Math.floor(num / 60);
        s = num % 60;
        h += "";
        s += "";
        h = (h.length == 1) ? "0" + h : h;
        s = (s.length == 1) ? "0" + s : s;
        self['weapon' + (index)].getChildByName("timerLabel").getComponent(cc.Label).string = h + ":" + s;
        if (num > 0) {
            num--;
            self.timer = setTimeout(self.showTime.bind(self), 1000, num, index);
        }
        else {
            self['weapon' + (index)].getChildByName("timerLabel").getComponent(cc.Label).string = "";
        }
    }
    //激活/关闭天赋
    public static activateTalent(self, id) {
        cc.log("activateTalent", self.talent1.getComponent(cc.Sprite))
        var talentData: any = LocalStorage.getObj("talent");
        var sp, url;
        for (let index in talentData) {
            if (id == talentData[index]['id']) {
                talentData[index]['state'] == 0 ? url = "image/skill 2" : url = "image/skill";
                sp = self["talent" + (Number(index) + 1)].getComponent(cc.Sprite);
            }
        }
        self.getSprite(url, sp);
    }
    public static upDataGold(self, data) {
        self.goldLabel.string = String(data);
    }
    //刷新武器显示
    private upDataWeaponUI() {

    }
    private getWeaponData(id) {
        var weaponData = LoadResData.weaponsData;
        for (let i = 0; i < weaponData.length; i++) {
            if (id == weaponData[i]["id"]) {
                return weaponData[i];
            }
        }
    }
    private getWeaponLv(id) {
        var weaponLv: any = LocalStorage.getObj("weaponLv");
        for (let i = 0; i < weaponLv.length; i++) {
            if (id == weaponLv[i]["id"]) {
                return weaponLv[i]["lv"];
            }
        }
    }
    private getSprite(url, sprite) {
        if (url == null) {
            return;
        }
        cc.loader.loadRes(url, cc.SpriteFrame, function (err, spriteFrame) {
            if (!err) {
                sprite.spriteFrame = spriteFrame;
            }
        });
    }
}
